package arcane.object.game.engine;

import java.awt.Dimension;

import javax.swing.JOptionPane;

import org.lwjgl.opengl.Display;

import com.golden.gamedev.Game;
import com.golden.gamedev.OpenGLGameLoader;
import com.golden.gamedev.engine.lwjgl.LWJGLInput;
import com.golden.gamedev.engine.lwjgl.LWJGLMode;
import com.golden.gamedev.engine.lwjgl.LWJGLTimer;
/**
 * OpenGLGameLoader for the ArcaneEngine.  The only change is in the LWJGLMode implementation.
 * The previous code had a bug which caused the game to crash when the frame, or resolution
 * was changed.
 * 
 * @author William Morrison
 *
 */
public class ArcaneGameLoader extends OpenGLGameLoader {
	/**
	 * Initializes OpenGL LWJGL graphics engine with specified size, mode, and
	 * associates it with specified <code>Game</code> object.
	 */
	public void setupLWJGL(Game game, Dimension d, boolean fullscreen,
			boolean vsync) {
		try {
			// validate java version first
			if (!validJavaVersion()) {
				// not valid java version!!
				JOptionPane
						.showMessageDialog(
								null,
								"Sorry, this game requires Java "
										+ MINIMUM_VERSION
										+ "++ installed\n"
										+ "Your machine only has Java "
										+ JAVA_VERSION
										+ " installed\n\n"
										+ "Please install the latest Java Runtime Edition (JRE)\n"
										+ "from http://www.java.com",
								"Game Initialization",
								JOptionPane.ERROR_MESSAGE);

				// don't bother to continue
				System.exit(-1);
			}

			// time to create the OpenGL Graphics Engine
			LWJGLMode mode = new LWJGLMode(d, fullscreen, vsync){
				public boolean flip(){
					if(Display.isCloseRequested()){
						this.getWindowListener().windowClosing(null);
					}
					Display.update();
					return true;
				}
			};
			mode.setWindowListener(this);

			gfx = mode;

			this.game = game;
			this.game.bsGraphics = gfx;
			this.game.bsInput = new LWJGLInput();
			this.game.bsTimer = new LWJGLTimer();

		} catch (Throwable e) {
			e.printStackTrace();

			JOptionPane.showMessageDialog(null,
					"Your machine does not support OpenGL via LWJGL!\n"
							+ "Caused by: " + e.toString() + "\n"
							+ "Fail back to Java2D Graphics Engine.",
					"Game Initialization", JOptionPane.ERROR_MESSAGE);

			if (gfx != null) {
				gfx.cleanup();
			}

			setup(game, d, fullscreen, false);
		}
	}

	/**
	 * Initializes OpenGL LWJGL graphics engine with specified size, mode, using
	 * vsync by default, and associates it with specified <code>Game</code>
	 * object.
	 */
	public void setupLWJGL(Game game, Dimension d, boolean fullscreen) {
		setupLWJGL(game, d, fullscreen, true);
	}

}
